package com.demo.modules.word.common.utils;

import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * @author MyPC
 */
@Component
public class AsposeUtil {


    /**
     * word转pdf
     *
     * @param inputStream word文件保存的路径
     * @param response    转换后pdf文件保存的路径
     * @author LCheng
     * @date 2020/12/25 13:51
     */
    @SneakyThrows
    public static void wordToPdf(InputStream inputStream, HttpServletResponse response, String fileName) {
        // response是HttpServletResponse对象
        response.setContentType("application/pdf;charset=utf-8");
        // test.docx是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".pdf");
        try (OutputStream outputStream = response.getOutputStream()) {
            Document doc = new Document(inputStream);
            doc.save(outputStream, SaveFormat.PDF);
        }
    }

    @SneakyThrows
    public static List<String> wordToImg(InputStream inputStream) {
        List<String> imageList = new ArrayList<>();
        Document doc = new Document(inputStream);
        int pageCount = doc.getPageCount();
        for (int i = 0; i < pageCount; i++) {
            Document pageInfo = doc.extractPages(i, 1);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            pageInfo.save(output, SaveFormat.PNG);
            String base64 = "data:image/png;base64," + Base64.getEncoder().encodeToString(output.toByteArray());
            imageList.add(base64);
        }
        return imageList;
    }
}